package org.lai;

import java.io.*;
import java.nio.file.Files;
import java.util.Random;
import com.aliyun.oss.ClientException;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.model.OSSObject;
import com.aliyun.oss.model.ObjectListing;
import com.aliyun.oss.model.OSSObjectSummary;

public class OssJavaSdkQuickStart {
    public static void main(String[] args) throws com.aliyuncs.exceptions.ClientException {
        // 设置 OSS Endpoint 和 Bucket 名称
        // 1.修改域名
        String endpoint = "https://oss-cn-beijing.aliyuncs.com";
        // 2.修改Bucket名称
        String bucketName = "studyspringboot";
        // 3.替换Bucket 区域
        String region = "cn-beijing";
        // 4.创建 OSSClient 实例
        EnvironmentVariableCredentialsProvider credentialsProvider =
                CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .region(region)
                .build();
        try {
            // 1. 上传文件
            File file = new File("D:\\学习文件\\晚上好.png");
//            2. 将文件转换成字节数组
            byte[] content = Files.readAllBytes(file.toPath());
            String objectName = "晚上好.png";
            // 3.调用OSSClient实例调用文件上传方法
            ossClient.putObject(bucketName, objectName, new ByteArrayInputStream(content));
            System.out.println("文件" + objectName + " 上传成功。");
            /**
             * 1.第一个参数：Bucket名称
             * 2.第二个参数：文件名称
             * 3.第三个参数：文件以字节数组的形式上传
             */

        } catch (Exception oe) {
           oe.getMessage();
        }finally {
            if (ossClient != null) {
                // 关闭OSSClient。
                ossClient.shutdown();
            }
        }
    }
}